package com.lxk.util.wxpay;

import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author JohnSoybean
 * @create 2020/4/16 16:48
 * @description 微信支付工具类
 */
public class MyWxPayUtil {

    /**
     * CFG 支付配置
     */
    public static String mchId = "1601213289";
    public static String api_key = "8f064ce01a5442e8a00fed9f69a5a975";

    public static String appId_MINI = "wxfacb13f8a3a00fe5";
    public static String appId_APP = "wx708b6b6876a71e98";

    /**
     * CFG WeChat支付回调地址 （非微信级别配置）
     */
    public final static String notify_url = "https://api.noxbase.com/api/wxpay/afterpay";

    /**
     * WeChat 退款回调地址
     */
    public final static String refund_notify_url = "http://api.mmayisx.com/wxpay/refund/notify";


    /**
     * -获取10位随机数
     * @return nonceStr
     */
    public static String getNonceStr(){
        return UUID.randomUUID().toString().replace("-","").substring(0, 10);
    }

    /**
     * -根据时间随机生成订单号
     * @return outTradeNo
     */
    public static String getOrderIdByTime() {
        Random rand = new Random();
        int shu2 = rand.nextInt(8999)+1000;
        DateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String shu1 = format.format(new Date());
        String shu0 = "WX";
        String randId = shu0 + shu1 + shu2;
        return randId;
    }

    /**
     * -获取客户端真实IP
     * @return ip
     */
    public static String getRemoteHost(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getRemoteAddr();
        }
        return ip.equals("0:0:0:0:0:0:0:1")?"127.0.0.1":ip;
    }

    /**
     * -提取统一下单的返回结果，转换成调用微信支付所需要的参数
     * @param resp
     * @return
     */
    public static Map<String, String> respToResult(Map<String, String> resp) {
        Map<String, String> map = new HashMap<String,String>();
        String packagepam = "prepay_id="+resp.get("prepay_id")+"";
        map.put("appId", resp.get("appid"));
        map.put("timeStamp", System.currentTimeMillis()+"");
        map.put("nonceStr", WXPayUtil.generateNonceStr());
        map.put("package", packagepam);
        map.put("signType", "MD5");
        String paySign = null;
        try {
            paySign = WXPayUtil.generateSignature(map, api_key);
        } catch (Exception e) {
            System.out.println("获取paySign失败！");
        }
        map.put("paySign", paySign);
        return map;
    }

    /**
     * -提取统一下单的返回结果，转换成调用微信支付所需要的参数
     * @param resp
     * @return
     */
    public static Map<String, String> respToResultApp(Map<String, String> resp) {
        Map<String, String> map = new HashMap<String,String>();
        map.put("appid", resp.get("appid"));
        map.put("partnerid", AppWxPayConfig.mchId);
        map.put("prepayid", resp.get("prepay_id"));
        map.put("timestamp", (System.currentTimeMillis()/1000)+"");
        map.put("noncestr", WXPayUtil.generateNonceStr());
        map.put("package", "Sign=WXPay");
        String sign = null;
        try {
            sign = WXPayUtil.generateSignature(map, api_key);
        } catch (Exception e) {
            System.out.println("获取sign失败！");
        }
        map.put("sign", sign);
        return map;
    }

}
